<template>
  <div>
    <el-dialog :title="titleComp" :visible="showProgress" @close="closeFn">
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="开启">
          <!-- active-value: 打开时的标识 inactive-value: 关闭时的标识 -->
          <el-switch
            v-model="formData.enVisible"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-row type="flex" justify="center">
          <el-button
            size="small"
            @click="$emit('update:showProgress', false)"
          >取 消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="addPrs"
          >确 定</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUserPerApi, updateRolePerApi } from '@/api'
export default {
  name: 'VueAdminTemplateMasterAddPermissions',
  props: {
    showProgress: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      formData: {
        name: '', // 权限名
        code: '', // 标识
        description: '', // 描述
        enVisible: '0', // 开关标识
        id: '' // 后台传来用来标识编辑
      },
      rules: { name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    titleComp() {
      return this.formData.id ? '编辑权限' : '新增权限'
    }
  },
  mounted() {

  },

  methods: {
    // 确定 -> 触发
    async addPrs() {
      try {
        await this.$refs.form.validate()
        // 判断否有 后台传来的id(通过id判断是新增还是添加)
        if (this.formData.id) {
          await updateRolePerApi(this.formData)
          this.$message.success('编辑权限成功！')
        } else {
          await addUserPerApi(this.formData)
          this.$message.success('添加权限成功！')
        }
        this.$emit('update:showProgress', false)
        await this.$parent.getPermissionList()
      } catch (error) {
        console.log(error)
      }
    },

    // 弹窗关闭触发
    closeFn() {
      this.$emit('update:showProgress', false)
      this.$refs.form.resetFields() // 移除校验规则
      this.formData = {
        name: '', // 权限名
        code: '', // 标识
        description: '', // 描述
        enVisible: '0', // 开关标识
        id: '' // 后台传来用来标识编辑
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
